package com.cskaoyan.gateway.controller.promo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.promo.PromoService;
import com.mall.promo.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author
 * @date 2020/12/26 17:13
 */
@RestController
@Slf4j
@RequestMapping("/shopping")
public class PromoController {
    @Reference(check = false)
    PromoService promoService;

    @GetMapping("seckilllist")
    @Anoymous
    public ResponseData seckilllist(SecKillListRequest request){
        SecKillListResponse response = promoService.sesckilllist(request);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }

    @PostMapping("promoProductDetail")
    public ResponseData promoProductDetail(@RequestBody PromoProductDetailRequest request){
        PromoProductDetailResponse response= promoService.promoProductDetail(request);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }

    /**
     * 秒杀下单的接口
     * @param secKillUserInfo
     * @return
     */
    @PostMapping("seckill")
    public ResponseData seckill(@RequestBody SecKillUserInfo secKillUserInfo, HttpServletRequest servletRequest){
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        Integer uid = (Integer) object.get("id");
        SecKillRequest request = new SecKillRequest();

        //请求参数封装
        request.setUserId(uid.longValue());
        request.setUsername(secKillUserInfo.getUserName());
        request.setPsId(secKillUserInfo.getPsId().longValue());
        request.setProductId(secKillUserInfo.getProductId().longValue());
        request.setAddressId(secKillUserInfo.getAddressId().longValue());
        request.setTel(secKillUserInfo.getTel());
        request.setStreetName(secKillUserInfo.getStreetName());

        SecKillResponse response = promoService.seckill(request);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }


}
